package com.gr.catanddog_common.utils.tokenUtils;

import com.alibaba.fastjson.JSON;
import lombok.Data;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

@Data
@Component
public class TokenSignature {
    String signature;
    String secrete = "admin";
    public TokenSignature(TokenPlayLoad tokenPlayload, TokenHeader tokenHeader) throws NoSuchAlgorithmException, InvalidKeyException {
        String playLoad = JSON.toJSONString(tokenPlayload);
        String header = JSON.toJSONString(tokenHeader);
        String str = Base64.getEncoder().encodeToString(playLoad.getBytes());
        String str1 = Base64.getEncoder().encodeToString(header.getBytes());
        signature = generateHmac(str+'.'+str1,secrete);
    }
    public static String generateHmac(String message, String secretKey) throws NoSuchAlgorithmException, InvalidKeyException {
        Mac mac = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        mac.init(secretKeySpec);
        byte[] hmacBytes = mac.doFinal(message.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(hmacBytes);
    }
}
